package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.SimpleRedisLock;
import com.hmdp.utils.UserHolder;
import io.lettuce.core.RedisClient;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private ISeckillVoucherService seckillVoucherService;

    @Resource
    private RedisIdWorker redisIdWorker;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedissonClient redissonClient;

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;

    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    // 创建线程池
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    private IVoucherOrderService proxy;

//  消息队列
    @PostConstruct
    private void init(){
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }

    private class VoucherOrderHandler implements Runnable{
        String queueName = "stream.orders";

        @Override
        public void run() {
            while (true){
                try {
                    // 1 获取消息队列中的订单信息 XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS stream.orders >
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create(queueName, ReadOffset.lastConsumed())
                    );
                    // 2 判断消息是否获取成功
                    if(list == null || list.isEmpty()){
                        // 2.1 没 -- 继续下一次循环
                        continue;
                    }
                    // 3 解析消息
                    MapRecord<String, Object, Object> mapRecord = list.get(0);
                    Map<Object, Object> values = mapRecord.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(values, new VoucherOrder(), true);
                    // 4 有 -- 处理订单
                    handleVoucherOrder(voucherOrder);
                    // 5 ACK确认 SACK stream.orders g1 id
                    stringRedisTemplate.opsForStream().acknowledge(queueName, "g1", mapRecord.getId());
                } catch (Exception e) {
                    log.error("处理订单异常", e);
                    handlePendingList();
                }
            }
        }

        private void handlePendingList(){
            while (true){
                try {
                    // 1 获取Pending-List中的订单信息 XREADGROUP GROUP g1 c1 COUNT 1 STREAMS stream.orders 0
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1),
                            StreamOffset.create(queueName, ReadOffset.from("0"))
                    );
                    // 2 判断Pending-List消息是否获取成功
                    if(list == null || list.isEmpty()){
                        // 2.1 没 -- 结束循环
                        break;
                    }
                    // 3 解析消息
                    MapRecord<String, Object, Object> mapRecord = list.get(0);
                    Map<Object, Object> values = mapRecord.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(values, new VoucherOrder(), true);
                    // 4 有 -- 处理订单
                    handleVoucherOrder(voucherOrder);
                    // 5 ACK确认 SACK stream.orders g1 id
                    stringRedisTemplate.opsForStream().acknowledge(queueName, "g1", mapRecord.getId());
                } catch (Exception e) {
                    log.error("处理订单异常", e);
                    try {
                        Thread.sleep(20);
                    } catch (InterruptedException ex) {
                        throw new RuntimeException(ex);
                    }
                }
            }
        }
    }




    private void handleVoucherOrder(VoucherOrder voucherOrder) {
        Long userId = voucherOrder.getUserId();
        RLock lock = redissonClient.getLock("order:" + userId);
        boolean isLock = lock.tryLock();

        if(!isLock){
            log.error("不允许重复下单!");
            return;
        }
        try {
            // 获取代理对象
            proxy.createVoucherOrder(voucherOrder);
        } finally {
            lock.unlock();;
        }
    }

    /**
     * 下单秒杀券--异步优化 -- stream消息队列
     */
    @Override
    public Result seckillVoucher(Long id) {
        // 用户id
        Long userId = UserHolder.getUser().getId();
        Long orderId = redisIdWorker.nextId("order");
        // 执行lua脚本判断库存和资格
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT, Collections.emptyList(),
                id.toString(), userId.toString(), String.valueOf(orderId));
        // 判断结果是否为0
        int r = result.intValue();
        if(r != 0){
            // 不为0 返回异常信息
            return Result.fail(r == 1 ? "库存不足!" : "不允许重复下单!");
        }
        // 获取代理对象
        proxy = (IVoucherOrderService) AopContext.currentProxy();

        return Result.ok(orderId);
    }

    // 阻塞队列
//    private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024 * 1024);

    // 阻塞队列
//    @PostConstruct
//    private void init(){
//        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
//    }
//    private class VoucherOrderHandler implements Runnable{
//
//        @Override
//        public void run() {
//            while (true){
//                try {
//                    // 1 获取队列中的订单信息
//                    VoucherOrder voucherOrder = orderTasks.take();
//                    // 2 处理订单
//                    handleVoucherOrder(voucherOrder);
//                } catch (Exception e) {
//                    log.error("处理订单异常", e);
//                }
//            }
//        }
//    }

    /**
     * 下单秒杀券--异步优化 -- 阻塞队列
     */
//    @Override
//    public Result seckillVoucher(Long id) {
//        // 用户id
//        Long userId = UserHolder.getUser().getId();
//        // 执行lua脚本判断库存和资格
//        Long result = stringRedisTemplate.execute(
//                SECKILL_SCRIPT, Collections.emptyList(), id.toString(), userId.toString());
//        // 判断结果是否为0
//        int r = result.intValue();
//        if(r != 0){
//            // 不为0 返回异常信息
//            return Result.fail(r == 1 ? "库存不足!" : "不允许重复下单!");
//        }
//        // 生成订单Id
//        long orderId = redisIdWorker.nextId("order");
//        VoucherOrder voucherOrder = new VoucherOrder();
//        voucherOrder.setId(orderId);
//        voucherOrder.setVoucherId(id);
//        voucherOrder.setUserId(userId);
//        // 将优惠券id用户id和订单id存入阻塞队列
//        orderTasks.add(voucherOrder);
//        // 获取代理对象
//        proxy = (IVoucherOrderService) AopContext.currentProxy();
//
//        return Result.ok(orderId);
//    }

//    @Override
//    public Result seckillVoucher(Long id) {
//        // 1.根据id查询秒杀券
//        SeckillVoucher seckillVoucher = seckillVoucherService.getById(id);
//        // 2.秒杀券是否在抢购开放时间
//        LocalDateTime beginTime = seckillVoucher.getBeginTime();
//        LocalDateTime endTime = seckillVoucher.getEndTime();
//        LocalDateTime now = LocalDateTime.now();
//        if(beginTime.isAfter(now)){
//            return Result.fail("不在开放时间！");
//        }
//        if(endTime.isBefore(now)){
//            return Result.fail("不在开放时间！");
//        }
//        // 3.秒杀券库存是否足够
//        Integer stock = seckillVoucher.getStock();
//        if(stock < 1){
//            return Result.fail("库存不足！");
//        }
//        Long userId = UserHolder.getUser().getId();
////        // 获取锁->提交事务->释放锁 才是安全的
////        synchronized (userId.toString().intern()){
////            // 获取代理对象（事务有关的代理对象）
////            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
////            return proxy.createVoucherOrder(id);
////        }
//        // Redis分布式锁 // 不可重入 无法重试 锁超时失效
////        SimpleRedisLock lock = new SimpleRedisLock(stringRedisTemplate, "order:" + userId);
//
//        // Redisson分布式锁  // √ hash结构可重入 信号量控制重试等待 watchdog延续锁时间  × redis宕机
//        RLock lock = redissonClient.getLock("order:" + userId);
//        boolean isLock = lock.tryLock();
//
//        if(!isLock){
//            return Result.fail("不允许重复下单！");
//        }
//        try {
//            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
//            return proxy.createVoucherOrder(id);
//        } finally {
//            lock.unlock();;
//        }
//    }

    @Transactional
    public void createVoucherOrder(VoucherOrder voucherOrder){
        // 一人一单
        Long userId = voucherOrder.getUserId();
        Long voucherId = voucherOrder.getVoucherId();
        int count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
        if(count > 0){
            log.error("您已经购买过了~");
        }
        // 4.库存减一
        boolean success = seckillVoucherService.update()
                .setSql("stock = stock - 1")
                .eq("voucher_id", voucherId)
                .gt("stock", 0).update();
        if(!success){
            log.error("库存不足！");
        }
        // 5.新增优惠券订单
        save(voucherOrder);
    }
}
